package com.zhang.controller.warehouse;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.common.util.result.R;
import com.zhang.common.util.result.RUtils;
import com.zhang.common.util.time.TimeUtils;
import com.zhang.goods.service.WareAndSkuService;

import com.zhang.system.entity.AdminUser;
import com.zhang.system.service.IAdminUserService;
import com.zhang.warehouse.dto.AssignmentDto;
import com.zhang.warehouse.dto.FinishDto;
import com.zhang.warehouse.dto.MergeDto;
import com.zhang.warehouse.entity.Purchase;
import com.zhang.warehouse.entity.PurchaseDetail;
import com.zhang.warehouse.service.IPurchaseDetailService;
import com.zhang.warehouse.service.IPurchaseService;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/warehouse/purchase/")
@Slf4j
public class PurchaseController {
    @Autowired
    private IPurchaseDetailService purchaseDetailService;
    @Autowired
    private IPurchaseService purchaseService;
    @Autowired
    private IAdminUserService adminUserService;
    @Autowired
    private WareAndSkuService wareAndSkuService;

    @PostMapping("add/purchaseDetail")
    public R addPurchaseDetail(@RequestBody PurchaseDetail purchaseDetail) {
        purchaseDetailService.save(purchaseDetail);
        return RUtils.successMsg("新增成功");
    }

    /**
     * 合并采购单
     *
     * @param mergeDto
     * @return {@link R}
     */
    @PostMapping("merge/purchaseDetail")
    public R mergePurchaseDetail(@RequestBody MergeDto mergeDto) {
        purchaseService.mergePurchaseDetail(mergeDto);
        return RUtils.successMsg("合并成功");
    }

    /**
     * 完成采购单
     *
     * @param finishDto
     * @return {@link R}
     */
    @PostMapping("finish/purchase")
    public R finishPurchase(@RequestBody FinishDto finishDto) {
        wareAndSkuService.finishPurchase(finishDto);
        return RUtils.successMsg("完成采购单!");
    }

    @GetMapping("get/purchaseDetail/list/condition")
    public R getPurchaseDetailPageList(@RequestParam Map searchDto) {
        return purchaseDetailService.getpurchaseDetailPageList(searchDto);
    }

    @PostMapping("add/purchase")
    public R addPurchase(@RequestBody Purchase purchase) {
        purchase.setCreateTime(TimeUtils.getLocalDateStr());
        purchaseService.save(purchase);
        return RUtils.successMsg("新增成功");
    }

    @PutMapping("modify/purchase")
    public R modifyPurchase(@RequestBody Purchase purchase) {
        purchase.setUpdateTime(TimeUtils.getLocalDateStr());
        purchaseService.updateById(purchase);
        return RUtils.successMsg("修改成功");
    }

    /**
     * 分配采购单
     *
     * @param assignmentDto
     * @return {@link R}
     */
    @PostMapping("assignment/purchase")
    public R PurchaseAssignment(@RequestBody AssignmentDto assignmentDto) {
        AdminUser byId = adminUserService.getById(assignmentDto.getAssigneeId());
        if (byId != null) {
            Purchase purchase = new Purchase();
            purchase.setId(assignmentDto.getPurchaseId());
            purchase.setAssigneeId(byId.getId());
            purchase.setAssigneeName(byId.getUserName());
            purchase.setPhone(byId.getPhone());
            purchase.setStatus(1);
            purchaseService.updateById(purchase);
            return RUtils.successMsg("分配成功");
        }
        return RUtils.err("分配失败");
    }

    @GetMapping("purchaseId")
    public R getPurchaseDetail(String purchaseId) {
        Purchase byId = purchaseService.getById(purchaseId);
        return RUtils.successData(byId);
    }

    @GetMapping("get/purchase/list/condition")
    public R getPurchasePageList(@RequestParam(required = false) Map searchDto) {
        return purchaseService.getpurchasePageList(searchDto);
    }

    @GetMapping("get/purchaseDetail/list/by/purchaseId")
    public R getPurchaseDetailListByPurchaseId(@RequestParam Long purchaseId) {
        List<PurchaseDetail> list = purchaseDetailService.getListByPurchaseId(purchaseId);
        return RUtils.successData(list);
    }

    /**
     * 获取登录人（已领取）的采购单
     *
     * @return {@link R}
     */
    @GetMapping("get/my/purchase/list")
    public R getMyPurchaseList() {
        List<Purchase> purchaseList = purchaseService.list(new QueryWrapper<Purchase>().eq("assignee_id", StpUtil.getLoginIdAsLong()));
        return RUtils.successData(purchaseList);
    }

    @GetMapping("get/purchase/unreceive/list")
    public R getPurchaseUnreceiveList() {
        QueryWrapper<Purchase> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);
        List<Purchase> list = purchaseService.list(wrapper);
        return RUtils.successData(list);
    }

    /**
     * 领取采购单
     *
     * @param purchaseIds
     * @return {@link R}
     */
    @PostMapping("receive/purchase")
    public R receivePurchase(@RequestBody List<Long> purchaseIds) {
        purchaseService.receivePurchase(purchaseIds);
        return RUtils.successMsg("领取成功!");
    }

    /**
     * TODO 简单导出，后续需要找一个excel工具类,暂时仅超级管理员使用
     *
     * @param response
     * @return {@link R}
     */
    @GetMapping("export")
//    @SaCheckRole("admin")
    void exportPurchase(HttpServletResponse response) {
        log.info("entry export api");
        List<Purchase> list = purchaseService.list();
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        // 设置响应头
        response.setHeader("Content-disposition", "attachment;filename=purchase.xlsx");
        try {
            EasyExcel.write(response.getOutputStream(), Purchase.class).sheet("采购单列表").doWrite(list);
        } catch (IOException e) {
            log.error("导出异常", e);
            throw new RuntimeException("导出失败！");
        }
    }

}
